<template>
  <div id="playerVideoDiv">
    <video id="videoPlayer" ref="videoRef" class="video-js vjs-16-9"></video>
  </div>
</template>

<script>
import 'video.js/dist/video-js.css'
import videojs from 'video.js'
import 'videojs-contrib-hls'
import { reactive, ref, nextTick } from 'vue'
export default {
  name: "VideoPlayer",
  props: {
    playerSrc: {
      type: String,
      required: true
    },
    playerMimetype: {
      type: String,
      default: 'video/mp4'
    }
  },
  emits: ['playEndHandle'],
  setup(props, context) {
    const playerOptions = reactive({
      autoplay: true,
      muted: false, // 设置了它为true，才可实现自动播放,同时视频也被静音 （Chrome66及以上版本，禁止音视频的自动播放）
      controls: true,
      fluid: true,
      preload: "auto",
      sources: [
        {
          src: '',
          type: ''
        }
      ]
    })
    const player = ref(null)
    const videoRef = ref(null)

    const handleDisposePlayer = () => {
      if (player.value != null) {
        player.value.dispose()
      }
      player.value = null
    }
    const handlePlayerVideo = () => {
      if (!player.value) {
        player.value = videojs(videoRef.value, playerOptions)
        player.value.ready(function () {
          console.log('onPlayerReady');

          // How about an event listener?
          this.on('ended', function () {
            // videojs.log('当前视频播放结束');
            // 执行
            context.emit('playEndHandle')
          });

          this.on("canplaythrough", function () {
            console.log("视频源数据加载完成")
            player.value.play()
          })

          this.on('error', function () {
            videojs.log('error');
            this.errorDisplay.contentEl().innerText = '不支持的 播放格式，播放失败'
            // 执行
            // context.emit('playEndHandle')
          });
        })
      }

    }
    const init = () => {
      nextTick(() => {
        playerOptions.sources[0].type = props.playerMimetype.indexOf('mp4') != -1 ? 'video/mp4' : props.playerMimetype
        playerOptions.sources[0].src = props.playerSrc
        handlePlayerVideo()
      })
    }

    return {
      init,
      handleDisposePlayer,
      videoRef,
      player
    }
  }
}
</script>

<style scoped>
#playerVideoDiv {
  width: 100%;
  /*max-height: 300px;*/
}
  #videoPlayer{
    height: 300px;
  }
</style>
